<?php

namespace app\admin\controller;

use app\admin\model\system\SystemAdmin;
use app\admin\model\system\SystemMenus;
use bbweb\basic\BaseController;
use think\facade\Route as Url;
use think\facade\Session;

/**
 * 基类 所有控制器继承的类
 * Class AuthController
 * @package app\admin\controller
 */
class AuthController extends BaseController
{
    /**
     * 当前登陆管理员信息
     * @var
     */
    protected $adminInfo;

    /**
     * 当前登陆管理员ID
     * @var
     */
    protected $adminId;

    /**
     * 当前管理员权限
     * @var array
     */
    protected $auth = [];

    protected $skipLogController = ['index'];

    protected function initialize()
    {
        parent::initialize();
        if (!SystemAdmin::hasActiveAdmin()) $this->redirect(Url::buildUrl('/login/index')->build());
        $adminInfo = SystemAdmin::activeAdminInfoOrFail();
        if(!$adminInfo || !$adminInfo['id']) {
            $this->error(SystemAdmin::getErrorInfo('请登陆!'), Url::buildUrl('/login/index')->build());
        }
        Session::set('login_at', time());
        Session::save();

        $this->adminInfo = $adminInfo;
        $this->adminId = $adminInfo['id'];
        if($this->adminId > 0) $this->getActiveAdminInfo();

        $this->auth = SystemAdmin::activeAdminAuthOrFail();
        $this->adminInfo['level'] === 0 || $this->checkAuth();
        $this->assign('_admin', $this->adminInfo);
        $type = 'system';
        if($this->adminId > 0) event('AdminVisit', [$this->adminInfo, $type]);
    }

    protected function checkAuth($action = null, $controller = null)
    {
        if ($controller === null) $controller = $this->request->controller();
        if ($action === null) $action = $this->request->action();
        if (in_array(strtolower($controller), $this->skipLogController, true)) return true;
        if (preg_match('/^public_/',$action) ) return true;
        $nowAuthName = SystemMenus::getAuthName($action, $controller);
        if (!in_array($nowAuthName, $this->auth)) {
            $this->error('没有权限访问!');
        }
        return true;
    }


    /**
     * 获得当前用户最新信息
     * return array
     */
    protected function getActiveAdminInfo()
    {
        $adminId = $this->adminId;
        $adminInfo = SystemAdmin::getValidAdminInfoOrFail($adminId);
        if (!$adminInfo) $this->error(SystemAdmin::getErrorInfo('请登陆!'), Url::buildUrl('/login/index')->build());
        $this->adminInfo = $adminInfo;
        SystemAdmin::setLoginInfo($adminInfo);
        return $adminInfo;
    }
}